package Fb;

import cn.tedu.sp1.Service.ItemService;
import cn.tedu.sp1.Web.Util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@Component
public class ItemFb implements FallbackProvider {
    @Override/*用于设置针对哪个后台服务 *号 对所有服务应用当前降级*/
    public String getRoute() {
        return "item-service";  /*针对item-service服务*/
    }

    @Override/*向客户端返回相应数据*/
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {/*包含响应数据*/
            @Override/*该方法返回状态码对象  200  Ok*/
            public HttpStatus getStatusCode() throws IOException {

                return HttpStatus.INTERNAL_SERVER_ERROR;/*返回报错（暂时写死）*/
            }

            @Override/*该方法只返回状态码   200 */
            public int getRawStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.value();/*获取状态码*/
            }

            @Override/*该方法返回状态码文本   ok */
            public String getStatusText() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();/*获取状态码对应文本*/
            }

            @Override/*此方法用于关闭下面流方法*/
            public void close() {
                /*BAIS不占用底层资源，不需要关闭*/
            }

            @Override/*设置协议体数据*/
            public InputStream getBody() throws IOException {
                String json = JsonResult.build().code(500).msg("后台服务器出错").toString();
                return new ByteArrayInputStream(json.getBytes("UTF-8"));/*转化为字节数组*/
            }

            @Override/*设置协议头数据*/
            public HttpHeaders getHeaders() {
                HttpHeaders h = new HttpHeaders();
                h.add("Content-Type","application/json;charset=UTF-8");
                return h;
            }
        };
    }
}
